#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash genewise-2.4.1.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum install -y  environment-modules libatomic wget glib2 glib2-devel

set -e
wget -t 0 -c -P $buildpath https://www.ebi.ac.uk/~birney/wise2/wise2.4.1.tar.gz 
tar xf $buildpath/wise2.4.1.tar.gz -C $buildpath && rm -rf $buildpath/wise2.4.1.tar.gz
cd $buildpath/wise2.4.1/src
find . -name  makefile | xargs sed -i 's/glib-config/pkg-config glib-2.0/'
sed -i 's/getline/getline_ReadSeqVars/g' ./HMMer2/sqio.c
sed -i 's/isnumber/isdigit/' models/phasemodel.c
sed -i -e 's/csh welcome.csh/sh welcome.csh/' \
       -e '25s/cc/clang/' \
       -e '40s/$/-fsigned-char -march=armv8.2-a/' makefile
sed -i 's/-ldyna_glib/-ldyna_glib `pkg-config --libs glib-2.0`/' models/makefile
make all | tee make.log
mkdir -p $installpath/wise2.4.1 && cp -r $buildpath/wise2.4.1/* $installpath/wise2.4.1

rm -rf $buildpath/wise2.4.1
cat>"$installpath/wise2.4.1/genewise_modulefiles"<<EOF
#%Module1.0
conflict genewise
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
        set modfile_path [file dirname \$modfile]
	    return \$modfile_path
    }
set pwd [getModulefileDir]
set GENEWISE \$pwd
setenv GENEWISE \$GENEWISE
prepend-path PATH \$GENEWISE/src/bin
prepend-path WISECONFIGDIR \$GENEWISE/wisecfg
EOF

